package com.quzi.kettle.activitise.main;

import java.io.File;
import java.util.List;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.httprequest.AsyncBean;
import com.example.httprequest.AsyncHttpUtilClient;
import com.loopj.android.http.RequestParams;
import com.quzi.kettle.MyApplication;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.BaseActivity;
import com.quzi.kettle.api.response.InfoListResponse;
import com.quzi.kettle.bean.http.Consultation;
import com.quzi.kettle.utils.ImageUtil;
import com.quzi.kettle.utils.ImageUtil.ImageCallback;
import com.quzi.kettle.view.TitleBarHandler;
import com.quzi.kettle.view.TitleBarView;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;

public class HealthInfosActivity extends BaseActivity {

	private String Path = Environment.getExternalStorageDirectory() + "/";
	private final static int UPDATE_UI = 0;

	private TitleBarView titleView;
	private ExpandableListAdapter adapter;
	private ExpandableListView lists;

	private Handler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_healthinfo);

		initTitleBar();

		lists = (ExpandableListView) findViewById(R.id.lists);
		handler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				// TODO Auto-generated method stub
				super.dispatchMessage(msg);
				switch (msg.what) {
				case UPDATE_UI:

					final List<Consultation> list = (List<Consultation>) msg.obj;
					adapter = new MyAdapter(list);
					lists.setAdapter(adapter);
					// lists.setOnChildClickListener(new OnChildClickListener()
					// {
					//
					// @Override
					// public boolean onChildClick(ExpandableListView parent,
					// View v, int groupPosition, int childPosition,
					// long id) {
					// Toast.makeText(getApplicationContext(),
					// list.get(groupPosition).getContent(),
					// Toast.LENGTH_SHORT).show();
					// return false;
					// }
					// });
					lists.setGroupIndicator(null);
					break;
				}
			}
		};

		net_queryInfo();

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		delete(new File(Path));
	}

	public static void delete(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				delete(childFiles[i]);
			}
			file.delete();
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initTitleBar() {
		// TODO Auto-generated method stub
		super.initTitleBar();
		titleView = (TitleBarView) findViewById(R.id.titleview);
		titleView.setTitle(getResources().getString(R.string.heathinfo));
		titleView.setTitleBarClickListener(new TitleBarHandler() {

			@Override
			public void ClickRight() {
				// TODO Auto-generated method stub

			}

			@Override
			public void ClickLeft() {
				finish();
			}
		});
	}

	class MyAdapter extends BaseExpandableListAdapter {

		private List<Consultation> list;

		public MyAdapter(List<Consultation> list) {
			this.list = list;
		}

		// 重写ExpandableListAdapter中的各个方法
		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return list.get(groupPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			// TODO Auto-generated method stub
			return groupPosition;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			return 1;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return list.get(groupPosition).getContent();
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public View getGroupView(final int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			View view = View.inflate(getApplicationContext(),
					R.layout.group_list, null);
			final ImageView im = (ImageView) view.findViewById(R.id.image);

			if (!fileIsExists(Path + "images"
					+ list.get(groupPosition).getUrl())) {
				ImageUtil.loadImage(Path + "images"
						+ list.get(groupPosition).getUrl(),
						MyApplication.imageUrl
								+ list.get(groupPosition).getUrl(),
						new ImageCallback() {

							@Override
							public void loadImage(Bitmap bitmap,
									String imagePath) {
								// TODO Auto-generated method stub
								Log.d("kettle", "bitmap = " + bitmap + "     "
										+ imagePath);
								list.get(groupPosition).setBitmap(bitmap);
								im.setImageBitmap(list.get(groupPosition)
										.getBitmap());
							}
						});
			}
			im.setImageBitmap(ImageUtil.getImageFromLocal(Path + "images"
					+ list.get(groupPosition).getUrl()));
			
			TextView title = (TextView) view.findViewById(R.id.title);
			title.setText(list.get(groupPosition).getTitle());
			return view;

		}

		@Override
		public void onGroupExpanded(int groupPosition) {
			super.onGroupExpanded(groupPosition);
			for (int i = 0; i < adapter.getGroupCount(); i++) {
				if (groupPosition != i) {
					lists.collapseGroup(i);
				}
			}

		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {

			View view = View.inflate(getApplicationContext(),
					R.layout.child_list, null);
			TextView info = (TextView) view.findViewById(R.id.info);
			TextView shareinfo = (TextView) view
					.findViewById(R.id.tv_info_share);
			info.setText(list.get(groupPosition).getContent());
			shareinfo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// Toast.makeText(getApplicationContext(), "share",
					// Toast.LENGTH_SHORT).show();
					// 初始化一个WXTextObject对象
					WXTextObject textObj = new WXTextObject();
					textObj.text = "sss";

					// 用WXTextObject对象初始化一个WXMediaMessage对象
					WXMediaMessage msg = new WXMediaMessage();
					msg.mediaObject = textObj;
					// 发送文本类型的消息时，title字段不起作用
					// msg.title = "Will be ignored";
					msg.description = "bbb";

					// 构造一个Req
					SendMessageToWX.Req req = new SendMessageToWX.Req();
					req.transaction = String.valueOf(System.currentTimeMillis());// buildTransaction("text");
																					// //
																					// transaction字段用于唯一标识一个请求
					req.message = msg;
					req.scene = SendMessageToWX.Req.WXSceneTimeline;
					// isTimelineCb.isChecked() ?
					// SendMessageToWX.Req.WXSceneTimeline
					// : SendMessageToWX.Req.WXSceneSession;

					// 调用api接口发送数据到微信
					MyApplication.getApi().sendReq(req);
					finish();

				}
			});
			return view;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}

	}

	private void net_queryInfo() {
		showLoadingDialog();

		AsyncHttpUtilClient.request(
				getApplicationContext(),
				new AsyncBean(AsyncHttpUtilClient.GET, MyApplication.url
						+ MyApplication.requestMap
								.get(MyApplication.HEALTH_INFO) + "?page=1",
						null, new RequestParams()),
				new InfoListResponse<List<Consultation>>() {

					@Override
					public void onFailure(int arg0, String arg1) {
						dissLoadingDialog();
						UIHandler.obtainMessage(TOASTMSG,
								getResources().getText(R.string.failed))
								.sendToTarget();
						;
					}

					@Override
					public void onSuccess(List list) {
						List<Consultation> infoList = list;

						handler.obtainMessage(UPDATE_UI, infoList)
								.sendToTarget();

						dissLoadingDialog();
					}

				});
	}

	public static boolean fileIsExists(String path) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				return false;
			}

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}

}
